package com.huatai.bpmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.util.concurrent.AtomicDouble;
import com.huatai.bpmn.commom.util.BaseCommService;
import com.huatai.bpmn.constant.PMPConstant;
import com.huatai.bpmn.entity.*;
import com.huatai.bpmn.entity.vo.*;
import com.huatai.bpmn.mapper.BasicLoadMapper;
import com.huatai.bpmn.service.*;
import com.huatai.common.entity.UserInfo;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.common.util.AuthUtil;
import com.huatai.common.util.BeanUtil;
import com.huatai.common.util.ObjectUtil;
import com.huatai.common.util.StringUtil;
import com.huatai.user.dubbo.UserDubboApi;
import com.huatai.user.entity.Department;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * <p>
 * 表单数据
 * </p>
 *
 * @author yxy
 * @since 2023-07-07
 */
@Slf4j
@Service
public class BasicLoadServiceImpl extends ServiceImpl<BasicLoadMapper, BasicLoadEntity> implements BasicLoadService {

	@Autowired
	private YYActivitiService yyActivitiService;
	@Autowired
	private YYFormService yyFormService;
	@Autowired
	private DicService dicService;
	@DubboReference(timeout = 30000, check = false, retries = 0)
	private UserDubboApi userDubboApi;
	@Autowired
	private BaseCommService baseCommService;
	@Autowired
	private BasicService basicService;
	@Autowired
	private YYBasicService yyBasicService;
	@Autowired
	private BasicLoadService basicLoadService;
	@Autowired
	private YYDataInfoService yyDataInfoService;
	@Autowired
	private YYExternalParameterService yyExternalParameterService;
	@Autowired
	private DeployFormMappingService deployFormMappingService;
	@Autowired
	private YYKeyHistoryService yyKeyHistoryService;

	/**
	 * 获取项目库数据
	 *
	 * @return
	 */
	@Override
	public IPage pageList(JSONObject data) {
		String place = data.getOrDefault("place", "").toString();
		int pgIndex = Integer.valueOf(data.getOrDefault("pgIndex", "1").toString());
		int pgSize = Integer.valueOf(data.getOrDefault("pgSize", "10").toString());
		if (StringUtil.isBlank(place)) {
			throw new RuntimeException("表单标识不能为空");
		}
		List<JSONObject> count = this.getBaseMapper().count(place);
		List<JSONObject> list = this.getBaseMapper().pageList(place, ((pgIndex) - 1) * pgSize, pgSize);

		IPage page = PageVo.getiPage(pgIndex, pgSize, count, list);
		return page;
	}

	@Override
	public List<JSONObject> listByPlaceAndBusinessKey(String place, String businessKey) {
		return this.getBaseMapper().listByPlaceAndBusinessKey(place, businessKey);
	}


	/**
	 * 表单数据新增
	 *
	 * @param data
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean add(JSONObject data, String place, String businessKey) {
//		String place = data.getOrDefault("place", "").toString();
//		String businessKey = data.getOrDefault("businessKey", "").toString();
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		//获取表单表头列表
		List<YYBasicEntity> list = yyBasicService.getColumList(place);


		ArrayList<BasicLoadEntity> array = new ArrayList<>();


		list.stream().forEach(x -> {
			String jsonKey = x.getJsonKey();
			String jsonValue = data.getOrDefault(jsonKey, "").toString();
			//前期投入的实施详情数据需要单独存储，再返回id给表格这边存储
			if (PMPConstant.PLACE_QQ_STAGE.equals(place) && jsonKey.equals("ss_info")) {

			}
			BasicLoadEntity basicLoadEntity = new BasicLoadEntity();

			basicLoadEntity.setFlowId(uuid);
			basicLoadEntity.setType(x.getType());
			basicLoadEntity.setJsonKey(jsonKey);
			basicLoadEntity.setJsonVal(jsonValue);
			basicLoadEntity.setJsonTitle(x.getJsonValue());
			basicLoadEntity.setPlace(place);
			basicLoadEntity.setBasicId(x.getId());
			basicLoadEntity.setSort(x.getSort());
			basicLoadEntity.setBusinessKey(businessKey);
			array.add(basicLoadEntity);
		});


		return this.saveBatch(array);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean update(JSONObject data, String businessKey) {

		/*List<BasicLoadEntity> list = this.listByFlowId(flowId);
		ArrayList<BasicLoadEntity> array = new ArrayList<>();
		list.stream().forEach(x -> {
			String jsonKey = x.getJsonKey();
			String jsonValue = data.getOrDefault(jsonKey, "").toString();
			x.setJsonVal(jsonValue);
		});*/
		return this.updateByBusinessKey(data, businessKey);
	}

	/**
	 * 表单数据删除
	 *
	 * @param businessKey
	 * @return
	 */
	@Override
	public boolean remove(String businessKey) {
		this.remove(new LambdaQueryWrapper<>(BasicLoadEntity.class).eq(BasicLoadEntity::getBusinessKey, businessKey));
		yyDataInfoService.removeByFlowId(businessKey);
		return true;
	}

	/**
	 * 表单数据新增多条数据  data参数place，businessKey（“审批id”）,表单对应key-value
	 *
	 * @param list
	 * @return
	 */
	@Override
	public boolean addList(List<JSONObject> list, String businessKey) {
		ArrayList<ArrayList<BasicLoadEntity>> arrayLists = new ArrayList<>();
		for (JSONObject data : list) {
			String place = data.getOrDefault("place", "xmjbxx").toString();
			//获取表单表头列表
			List<BasicEntity> BasicEntityList = basicService.getColumList(place);
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");

			ArrayList<BasicLoadEntity> array = new ArrayList<>();
			BasicEntityList.stream().forEach(x -> {
				String jsonKey = x.getJsonKey();
				String jsonValue = data.getOrDefault(jsonKey, "").toString();
				BasicLoadEntity basicLoadEntity = new BasicLoadEntity();

				basicLoadEntity.setFlowId(uuid);
				basicLoadEntity.setType(x.getType());
				basicLoadEntity.setJsonKey(jsonKey);
				basicLoadEntity.setJsonVal(jsonValue);
				basicLoadEntity.setJsonTitle(x.getJsonValue());
				basicLoadEntity.setPlace(place);
				basicLoadEntity.setBasicId(x.getId());
				basicLoadEntity.setSort(x.getSort());
				basicLoadEntity.setBusinessKey(businessKey);
				array.add(basicLoadEntity);
			});
			arrayLists.add(array);
		}
		int rows = 0;
		for (ArrayList<BasicLoadEntity> arrayList : arrayLists) {
			boolean b = this.saveBatch(arrayList);
			if (b) {
				rows += 1;
			}
		}

		return rows > 0 ? true : false;
	}

	/**
	 * 创建任务时存在多个表单
	 *
	 * @param map
	 * @param businessKey
	 * @return
	 */
	@Override
	public boolean addList(HashMap<String, List<JSONObject>> map, String businessKey) {
		Set<String> places = map.keySet();
		boolean flag = true;
		for (String place : places) {
			List<JSONObject> list = map.get(place);
			flag = this.addList(place, list, businessKey);
		}
		return flag;
	}

	@Override
	public boolean addList(String place, List<JSONObject> list, String businessKey) {
		ArrayList<ArrayList<BasicLoadEntity>> arrayLists = new ArrayList<>();
		for (JSONObject data : list) {
			//获取表单表头列表
			List<BasicEntity> BasicEntityList = basicService.getColumList(place);
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");

			ArrayList<BasicLoadEntity> array = new ArrayList<>();
			BasicEntityList.stream().forEach(x -> {
				String jsonKey = x.getJsonKey();
				String jsonValue = data.getOrDefault(jsonKey, "").toString();
				BasicLoadEntity basicLoadEntity = new BasicLoadEntity();

				basicLoadEntity.setFlowId(uuid);
				basicLoadEntity.setType(x.getType());
				basicLoadEntity.setJsonKey(jsonKey);
				basicLoadEntity.setJsonVal(jsonValue);
				basicLoadEntity.setJsonTitle(x.getJsonValue());
				basicLoadEntity.setPlace(place);
				basicLoadEntity.setBasicId(x.getId());
				basicLoadEntity.setSort(x.getSort());
				basicLoadEntity.setBusinessKey(businessKey);
				array.add(basicLoadEntity);
			});
			arrayLists.add(array);
		}
		int rows = 0;
		for (ArrayList<BasicLoadEntity> arrayList : arrayLists) {
			boolean b = this.saveBatch(arrayList);
			if (b) {
				rows += 1;
			}
		}

		return rows > 0 ? true : false;
	}


	/**
	 * 根据BusinessKey获取数据
	 *
	 * @param data
	 * @return
	 */
	@Override
	public List<JSONObject> pageListByBusinessKey(JSONObject data) {
		String businessKey = data.getOrDefault("businessKey", "").toString();
		String place = data.getOrDefault("place", "").toString();
		if (StringUtil.isBlank(businessKey)) {
			throw new RuntimeException("businessKey不能为空");
		}
		List<JSONObject> list = this.getBaseMapper().listByPlaceAndBusinessKey(place, businessKey);
		return list;
	}

	/**
	 * 表单数据新增多条数据  data参数place，businessKey（“审批id”）,表单对应key-value
	 *
	 * @param data
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateList(List<JSONObject> data, String businessKey) {
		this.remove(new LambdaQueryWrapper<>(BasicLoadEntity.class).eq(BasicLoadEntity::getBusinessKey, businessKey));
		return this.addList(data, businessKey);
	}


	/**
	 * 根据flowId查询表单数据
	 *
	 * @param flowId
	 * @return
	 */
	public List<BasicLoadEntity> listByFlowId(String flowId) {
		return this.list(new LambdaQueryWrapper<>(BasicLoadEntity.class).eq(BasicLoadEntity::getFlowId, flowId));
	}

	@Override
	public List<String> findPlaceByBusinessKey(String businessKey) {
		return this.getBaseMapper().listByPlace(businessKey);
	}

	/*@Override
	public HashMap<String, Object> createTask(String externalParameterId,String deployId) {

		ExternalParameterEntity externalParameterEntity = externalParameterService.getById(externalParameterId);
		if (ObjectUtil.isEmpty(externalParameterEntity)){
			throw new RuntimeException("外部参数不能为空");
		}
		String[] placeArr = externalParameterEntity.getPlace().split(",");

		HashMap<String, Object> paramMap = new HashMap<>();//存储表头和外部参数
		HashMap<String, Object> map = new HashMap<>();//存储表头
		Arrays.stream(placeArr).forEach(place->{
			//获取表单表头
			List<BasicEntity> colum = basicService.getColum(place);
			FormEntity formEntity = formService.getByPlace(place);
			HashMap<String, Object> dataMap = new HashMap<>();
			dataMap.put("colum",colum);
			dataMap.put("name",formEntity.getName());
			map.put(place,dataMap);
		});

		String param = JSONObject.toJSONString(externalParameterEntity.getParam());
		paramMap.put("param",externalParameterEntity.getParam());
		paramMap.put("column",map);
		return paramMap	;
	}*/


	/**
	 * 项目数据查询
	 *
	 * @param dataVo
	 */
	@Override
	public JSONObject pageDataList(DataVo dataVo) {

		int pgIndex = dataVo.getPgIndex();
		int pgSize = dataVo.getPgSize();
		String myKey = dataVo.getMyKey();
		String departName = dataVo.getDepartName();//部门名称

		UserInfo user = AuthUtil.getUser();
		//获取所有表项目数据的flowId，再根据flowId查询数据
		JSONObject flowJson = yyDataInfoService.getDataList(myKey, user, departName, pgIndex, pgSize, dataVo);
		String total = flowJson.getOrDefault("total", "0").toString();
		JSONArray flowList = flowJson.getJSONArray("flowList");
		List<String> businessList = new ArrayList<>();
		if (flowList.size() > 0) {
			businessList = flowList.toJavaList(String.class);
		}

		DeployFormMappingEntity deployFormMapping = deployFormMappingService.getByMyKey(myKey);
		if (ObjectUtil.isEmpty(deployFormMapping)) {
			throw new RuntimeException("流程定义表单key错误");
		}
		//拿到表单配置信息
		YYExternalParameterEntity yyExternalParameterEntity = yyExternalParameterService.getById(deployFormMapping.getExternalParameterId());
		if (ObjectUtil.isEmpty(yyExternalParameterEntity)) {
			throw new RuntimeException("没有查询到项目表单配置");
		}
		String str = "(\"\",";
		String basicInfo = yyExternalParameterEntity.getBasicInfo();
		if (StringUtil.isEmpty(basicInfo)) {
			throw new RuntimeException("表头配置为空");
		}
		String[] arr = basicInfo.split(",");
		for (String s : arr) {
			str += "\"" + s + "\"" + ",";
		}
		str = str.substring(0, str.length() - 1);
		str += ")";
		JSONObject json = new JSONObject();
		//获取配置表头
		List<YYBasicEntity> basicList = basicService.getBasicList(str);
		//根据表头获取数据
		String place = yyExternalParameterEntity.getPlace();
		ArrayList<JSONObject> data = getData(basicList, place, businessList);
		json.put("column", basicList);
		json.put("data", data);
		json.put("total", total);
		return json;
	}

	/**
	 * 数据转入实施库
	 *
	 * @param businessKey
	 * @return
	 */
	@Override
	public boolean shiftSS(String businessKey, String myKey) {
		DeployFormMappingEntity deployFormMappingEntity = deployFormMappingService.getByMyKey(myKey);
		YYExternalParameterEntity externalParameterEntity = yyExternalParameterService.getById(deployFormMappingEntity.getExternalParameterId());
		//商机转入库-实施-黑名单-预警，数据place需要转为指定的基本表
		YYDataInfoEntity yyDataInfoEntity = yyDataInfoService.getBusinessKey(businessKey);
		if (yyDataInfoEntity.getStatus().equals(PMPConstant.STATUS_1)) {
			throw new ServiceException("数据操作中，不能转库");
		}
		if (PMPConstant.TABLE_SJ.equals(yyDataInfoEntity.getMyKey())) {

			this.getBaseMapper().updatePlaceByBus(externalParameterEntity.getPlace(), businessKey);
		}
		if (PMPConstant.TABLE_HMD.equals(yyDataInfoEntity.getMyKey())) {

			this.getBaseMapper().updatePlaceByBusByHMD(externalParameterEntity.getPlace(), businessKey);
		}
		return yyDataInfoService.shiftSS(businessKey, myKey);
	}


	/**
	 * 查看详情
	 *
	 * @param businessKey
	 * @return
	 */
	@Override
	public HashMap<String, Object> getInfo(String myKey, String businessKey) {
		DeployFormMappingEntity deployFormMappingEntity = deployFormMappingService.getByMyKey(myKey);

		String externalParameterId = deployFormMappingEntity.getExternalParameterId();
		//获取项目表单配置
		YYExternalParameterEntity externalParameterEntity = yyExternalParameterService.getById(externalParameterId);
		if (ObjectUtil.isEmpty(externalParameterEntity)) {
			throw new RuntimeException("外部参数id错误");
		}
		String[] placeArr = getStrings(externalParameterEntity.getTableInfo());
		ArrayList<YYFormEntity> placeList = new ArrayList<>();
		for (String s : placeArr) {
			YYFormEntity byPlace = yyFormService.getByPlace(s);
			placeList.add(byPlace);
		}
		List<String> collect = placeList.stream().sorted(Comparator.comparing(YYFormEntity::getSort)).map(x -> x.getPlace()).collect(Collectors.toList());
		String place = externalParameterEntity.getPlace();

		HashMap<String, Object> paramMap = new HashMap<>();//存储表头和外部参数
		LinkedHashMap<String, HashMap<String, Object>> map = new LinkedHashMap<>();//存储表头
		collect.forEach(table -> {
			//获取表单表头
			List<YYBasicEntity> colum = yyBasicService.getColum(table);
			ArrayList<YYBasicEntityVo> list = new ArrayList<>();
			for (YYBasicEntity yyBasicEntity : colum) {
				String jsonKey = yyBasicEntity.getJsonKey();
				//归口部门
				if (jsonKey.equals("gkbm")) {
					List<cn.hutool.json.JSONObject> childrenList = userDubboApi.getDepartList();
					YYBasicEntityVo yyBasicEntityVo = new YYBasicEntityVo();
					BeanUtil.copy(yyBasicEntity, yyBasicEntityVo);
					yyBasicEntityVo.setChildren(childrenList);
					list.add(yyBasicEntityVo);
					continue;
				}

				YYBasicEntityVo yyBasicEntityVo = new YYBasicEntityVo();
				BeanUtil.copy(yyBasicEntity, yyBasicEntityVo);
				if (!StringUtil.isEmpty(yyBasicEntity.getSelectItem())) {
					List<cn.hutool.json.JSONObject> childrenList = dicService.findChildrenData(yyBasicEntity.getSelectItem());
					yyBasicEntityVo.setChildren(childrenList);
				}
				list.add(yyBasicEntityVo);
			}
			YYFormEntity formEntity = yyFormService.getByPlace(table);
			HashMap<String, Object> dataMap = new HashMap<>();
			dataMap.put("colum", list);
			dataMap.put("name", formEntity.getName());
			dataMap.put("allowChange", true);

			map.put(table, dataMap);
		});

		List<YYBasicEntity> colum = yyBasicService.getColum(place);
		ArrayList<YYBasicEntityVo> list = new ArrayList<>();
		for (YYBasicEntity yyBasicEntity : colum) {
			String jsonKey = yyBasicEntity.getJsonKey();
			//归口部门
			if (jsonKey.equals("gkbm")) {
				List<cn.hutool.json.JSONObject> childrenList = userDubboApi.getDepartList();
				YYBasicEntityVo yyBasicEntityVo = new YYBasicEntityVo();
				BeanUtil.copy(yyBasicEntity, yyBasicEntityVo);
				yyBasicEntityVo.setChildren(childrenList);
				list.add(yyBasicEntityVo);
				continue;
			}
			DicEntity dicEntity = dicService.getCode(jsonKey);
			YYBasicEntityVo yyBasicEntityVo = new YYBasicEntityVo();
			BeanUtil.copy(yyBasicEntity, yyBasicEntityVo);
			if (!ObjectUtil.isEmpty(dicEntity)) {
				List<cn.hutool.json.JSONObject> childrenList = dicService.findChildrenData(dicEntity.getId());
				yyBasicEntityVo.setChildren(childrenList);
			}
			list.add(yyBasicEntityVo);
		}
		List<YYBasicEntity> basicList = yyBasicService.getColumList(place);
		String basicStr = "";
		for (YYBasicEntity yyBasicEntity : basicList) {
			String jsonKey = yyBasicEntity.getJsonKey();
			basicStr += "MAX(IF(json_key = \"" + jsonKey + "\", json_val, NULL)) AS \"" + jsonKey + "\",";
		}
		basicStr = basicStr.substring(0, basicStr.length() - 1);
		basicStr += ",business_key";
		YYDataInfoEntity yyDataInfoEntity = yyDataInfoService.getBusinessKey(businessKey);
		//表单数据-这里行转列容易出现未知的问题，不建议用
//		JSONObject paramData = this.getBaseMapper().getParamData(businessKey, place);
		JSONObject paramData = this.getBaseMapper().getParamData1(businessKey, basicStr);
		paramData.put("place", place);
		paramData.put("status", yyDataInfoEntity.getStatus());
		JSONObject columnData = new JSONObject(true);
		//表格数据
		Arrays.stream(placeArr).forEach(x -> {
			List<JSONObject> json = this.getBaseMapper().getColumnData(businessKey, x);
			columnData.put(x, json);
		});
		//查询值的历史变化
//		List<YYKeyHistoryEntity> keyList = yyKeyHistoryService.list(Wrappers.<YYKeyHistoryEntity>lambdaQuery().eq(YYKeyHistoryEntity::getBusinessKey, businessKey));
		List<JSONObject> keyList = yyKeyHistoryService.listByBusinessKey(businessKey);
		paramMap.put("history", keyList);
		paramMap.put("param", list);
		paramMap.put("column", map);
		paramMap.put("paramData", paramData);
		paramMap.put("columnData", columnData);
		return paramMap;
	}


	@Override
	public boolean removeByFlowId(String flowId) {
		String place = this.getBaseMapper().getPlace("flowId");
		//删除项目附件中的文件
		if ("xmfj".equals(place)) {
			BasicLoadEntity basicLoad = this.getOne(Wrappers.<BasicLoadEntity>lambdaQuery().eq(BasicLoadEntity::getFlowId, flowId).eq(BasicLoadEntity::getJsonKey, "file_path"));
			yyActivitiService.fileDelete(basicLoad.getJsonVal());
		}
		return this.remove(Wrappers.<BasicLoadEntity>lambdaQuery().eq(BasicLoadEntity::getFlowId, flowId));
	}

	/**
	 * 表格数据修改-表单表格
	 *
	 * @param businessKey
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateByBusinessKey(JSONObject jsonObject, String businessKey) {
		String place = jsonObject.getOrDefault("place", "xmjbxx").toString();
		String flowId = jsonObject.getOrDefault("flow_id", "").toString();
		if (StringUtil.isEmpty(flowId)) {
			this.removeForm(place, businessKey);//删除所有表单数据
		} else {
			this.removeFormByFlowId(flowId, businessKey);//删除所有表单数据
		}

		//新增表单数据
		this.add(jsonObject, place, businessKey);
		//新增字段记录
		String yjje = jsonObject.getOrDefault("yjldje", "0").toString();
		YYKeyHistoryEntity keyHistoryEntity = yyKeyHistoryService.list(Wrappers.<YYKeyHistoryEntity>lambdaQuery()
			.eq(YYKeyHistoryEntity::getHisKey, "预计落地金额").eq(YYKeyHistoryEntity::getBusinessKey, businessKey).orderByDesc(YYKeyHistoryEntity::getCreateTime)).stream().findFirst().orElse(null);
		if (ObjectUtil.isEmpty(keyHistoryEntity)) {
			saveHistory(businessKey, yjje);
		} else {
			if (!yjje.equals(keyHistoryEntity.getHisValue())) {
				saveHistory(businessKey, yjje);
			}
		}

//		yyActivitiService.startProcess(jsonObject,businessKey);
		return true;
	}

	private void saveHistory(String businessKey, String yjje) {
		YYKeyHistoryEntity yyKeyHistoryEntity = new YYKeyHistoryEntity();
		yyKeyHistoryEntity.setHisKey("预计落地金额");
		yyKeyHistoryEntity.setHisValue(yjje);
		yyKeyHistoryEntity.setBusinessKey(businessKey);
		yyKeyHistoryEntity.setCreateTime(LocalDateTime.now());
		yyKeyHistoryService.save(yyKeyHistoryEntity);
	}


	private void removeForm(String place, String businessKey) {
		this.remove(Wrappers.<BasicLoadEntity>lambdaQuery().eq(BasicLoadEntity::getBusinessKey, businessKey).eq(BasicLoadEntity::getPlace, place));
	}

	private void removeFormByFlowId(String flowId, String businessKey) {
		this.remove(Wrappers.<BasicLoadEntity>lambdaQuery().eq(BasicLoadEntity::getBusinessKey, businessKey).eq(BasicLoadEntity::getFlowId, flowId));
	}

	private String[] getStrings(String arrStr) {
		if (StringUtil.isEmpty(arrStr)) {
			return new String[]{};
		}
		return arrStr.split(",");
	}

	/**
	 * 根据表单-表头获取数据
	 *
	 * @param place
	 */
	private ArrayList<JSONObject> getData(List<YYBasicEntity> basicList, String place, List<String> businessList) {
		String str = "(\"\",";
		for (YYBasicEntity yyBasicEntity : basicList) {
			str += "\"" + yyBasicEntity.getJsonKey() + "\"" + ",";
		}
		str = str.substring(0, str.length() - 1);
		str += ")";
		String finalStr = str;
		ArrayList<JSONObject> lists = new ArrayList<>();
		String basicStr = "";
		for (YYBasicEntity yyBasicEntity : basicList) {
			String jsonKey = yyBasicEntity.getJsonKey();
			basicStr += "MAX(IF(json_key = \"" + jsonKey + "\", json_val, NULL)) AS \"" + jsonKey + "\",";
		}
		basicStr = basicStr.substring(0, basicStr.length() - 1);
		basicStr += ",business_key";
		String finalBasicStr = basicStr;
		businessList.forEach(x -> {
			if ("sjjbxx".equals(place)) {
				JSONObject jsonObject = this.getBaseMapper().listFlowIds(x, finalStr, "xmjbxx", finalBasicStr);
				if (!ObjectUtil.isEmpty(jsonObject)) {
					lists.add(jsonObject);
				}
			}

//			List<JSONObject> jsonObject=this.getBaseMapper().listByFlowId(x,finalStr,place);
			JSONObject jsonObject = this.getBaseMapper().listFlowIds(x, finalStr, place, finalBasicStr);
			if (!ObjectUtil.isEmpty(jsonObject)) {
				lists.add(jsonObject);
			}

		});
		return lists;
	}

	/**
	 * 数据分析-项目总览
	 */
	@Override
	public JSONObject dataAnalyse(int year) {
		UserInfo user = AuthUtil.getUser();

		JSONObject json = new JSONObject();
		//如果用户角色为总经理-市场部-财务部则可以查看全部项目
		if (PMPConstant.USER_POST_ZJL.equals(user.getPostId().toString()) ||
			PMPConstant.DEPART_CWB_ID.equals(user.getDeptId().toString()) ||
			PMPConstant.DEPART_SCB_ID.equals(user.getDeptId().toString())) {
			json = AllDataAnalyse(year);
			JSONObject jsonObject = getStatistics(year);
			json.put("statistics", jsonObject);
			return json;
		}
		Long deptId = user.getDeptId();
		Department department = userDubboApi.getDepart(deptId);
		String deptName = department.getDeptName();
		//获取部门信息，判断部门领导是不是当前用户
		if (ObjectUtil.isEmpty(department)) {
			throw new RuntimeException("请给用户赋予部门和角色");
		}
		////部门老大-主任-总工程师可以查看部门所有数据
		if (PMPConstant.USER_POST_ZR.equals(user.getPostId().toString()) || PMPConstant.USER_POST_FZR.equals(user.getPostId().toString()) || PMPConstant.USER_POST_ZGCS.equals(user.getPostId().toString())) {
			json = getDataAnalyse(deptName, year);
			JSONObject jsonObject = getStatistic(year, deptName);
			json.put("statistics", jsonObject);
		}

		return json;
	}


	private JSONObject getStatistic(int year, String deptName) {
		//获取到所有的数据
		List<String> sjList = this.getBaseMapper().getSJDeptList(year, deptName);
		List<String> rkList = this.getBaseMapper().getRkDeptList(year, deptName);
		List<String> tdList = this.getBaseMapper().getTDDeptList(year, deptName, PMPConstant.TABLE_TD);
		rkList.remove("");
		sjList.remove("");
		String str = "(\"";
		str += sjList.stream().collect(Collectors.joining("\",\""));
		//商机数据不用统，后续要统放开即可
//		str += "\",\"";
//		str += sjList.stream().collect(Collectors.joining("\",\""));
		str += "\")";
		List<String> add = this.getBaseMapper().getKeyCount("xmlx", "新增", str);
		List<String> save = this.getBaseMapper().getKeyCount("xmlx", "存量", str);
		List<String> A = this.getBaseMapper().getKeyCount("xmdj", "A", str);
		List<String> B = this.getBaseMapper().getKeyCount("xmdj", "B", str);
		List<String> C = this.getBaseMapper().getKeyCount("xmdj", "C", str);


		List<JSONObject> listJson = this.getBaseMapper().getRkListByMoney(str);
		ArrayList<String> list = new ArrayList<>();
		list.add("");
		list.add("新增项目");
		list.add("存量项目");
		list.add("预计落地金额（新增）");
		list.add("预计营收（新增、存量））");
		list.add("预计回款（新增、存量）");

//		String yjje=this.getBaseMapper().getCountAddByMoney("yjje",str);
//		String yjldje=this.getBaseMapper().getCountAddByMoney("yjldje",str);
//		String yjys=this.getBaseMapper().getCountByMoney("yjys",str);
//		String yjhk=this.getBaseMapper().getCountByMoney("yjhk",str);
		double addNum = 0;
		double saveNum = 0;
		double yjldNum = 0;
		double yjysNum = 0;
		double yjhkNum = 0;
		for (JSONObject jsonObject : listJson) {
			String xmlx = jsonObject.getOrDefault("xmlx", "新增").toString();
			String yjje = jsonObject.getOrDefault("yjje", "0").toString();
			String yjld = jsonObject.getOrDefault("yjldje", "0").toString();
			String yjys = jsonObject.getOrDefault("yjys", "0").toString();
			String yjhk = jsonObject.getOrDefault("yjhk", "0").toString();
			yjje = "".equals(yjje) ? "0" : yjje;
			yjld = "".equals(yjld) ? "0" : yjld;
			yjys = "".equals(yjys) ? "0" : yjys;
			yjhk = "".equals(yjhk) ? "0" : yjhk;
			if ("新增".equals(xmlx)) {
				addNum += 1;
				yjldNum += Double.valueOf(yjld);
				yjysNum += Double.valueOf(yjys);
				yjhkNum += Double.valueOf(yjhk);
			} else {
				saveNum += 1;
			}

		}
		ArrayList<String> list1 = new ArrayList<>();
		list1.add("全量");
		list1.add(String.valueOf(addNum));
		list1.add(String.valueOf(saveNum));
		list1.add(String.valueOf(yjldNum));
		list1.add(String.valueOf(yjysNum));
		list1.add(String.valueOf(yjhkNum));

		double aAdd = 0;
		double bAdd = 0;
		double cAdd = 0;
		double aSave = 0;
		double bSave = 0;
		double cSave = 0;
		double aYjld = 0;
		double bYjld = 0;
		double cYjld = 0;
		double aYjys = 0;
		double bYjys = 0;
		double cYjys = 0;
		double aYjhk = 0;
		double bYjhk = 0;
		double cYjhk = 0;
		for (JSONObject jsonObject : listJson) {
			String xmlx = jsonObject.getOrDefault("xmlx", "新增").toString();
			String yjje = jsonObject.getOrDefault("yjje", "0").toString();
			String yjld = jsonObject.getOrDefault("yjldje", "0").toString();
			String yjys = jsonObject.getOrDefault("yjys", "0").toString();
			String yjhk = jsonObject.getOrDefault("yjhk", "0").toString();
			String xmdj = jsonObject.getOrDefault("xmdj", "A").toString();
			yjje = "".equals(yjje) ? "0" : yjje;
			yjld = "".equals(yjld) ? "0" : yjld;
			yjys = "".equals(yjys) ? "0" : yjys;
			yjhk = "".equals(yjhk) ? "0" : yjhk;
			xmdj = "".equals(xmdj) ? "0" : xmdj;
			switch (xmdj) {
				case "A":

					if ("新增".equals(xmlx)) {
						aAdd += 1;
						aYjys += Double.valueOf(yjys);
						aYjhk += Double.valueOf(yjhk);
						aYjld += Double.valueOf(yjld);
					} else {
						aSave += 1;
					}
					break;
				case "B":

					if ("新增".equals(xmlx)) {
						bAdd += 1;
						bYjys += Double.valueOf(yjys);
						bYjhk += Double.valueOf(yjhk);
						bYjld += Double.valueOf(yjld);
					} else {
						bSave += 1;
					}
					break;
				case "C":

					if ("新增".equals(xmlx)) {
						cAdd += 1;
						cYjys += Double.valueOf(yjys);
						cYjhk += Double.valueOf(yjhk);
						cYjld += Double.valueOf(yjld);
					} else {
						cSave += 1;
					}
					break;
			}
		}
		ArrayList<String> list2 = new ArrayList<>();
		list2.add("A类");
		list2.add(String.valueOf(aAdd));
		list2.add(String.valueOf(aSave));
		list2.add(String.format("%.2f", aYjld));
		list2.add(String.format("%.2f", aYjys));
		list2.add(String.format("%.2f", aYjhk));
		ArrayList<String> list3 = new ArrayList<>();
		list3.add("B类");
		list3.add(String.valueOf(bAdd));
		list3.add(String.valueOf(bSave));
		list3.add(String.format("%.2f", bYjld));
		list3.add(String.format("%.2f", bYjys));
		list3.add(String.format("%.2f", bYjhk));
		ArrayList<String> list4 = new ArrayList<>();
		list4.add("C类");
		list4.add(String.valueOf(cAdd));
		list4.add(String.valueOf(cSave));
		list4.add(String.valueOf(cYjld));
		list4.add(String.valueOf(cYjys));
		list4.add(String.valueOf(cYjhk));
		list4.add(String.format("%.2f", cYjld));
		list4.add(String.format("%.2f", cYjys));
		list4.add(String.format("%.2f", cYjhk));
		ArrayList<ArrayList> arrayLists = new ArrayList<>();
		arrayLists.add(list);
		arrayLists.add(list1);
		arrayLists.add(list2);
		arrayLists.add(list3);
		arrayLists.add(list4);
		JSONObject json = new JSONObject();
		json.put("sj", sjList.size());
		json.put("rk", rkList.size());
		json.put("td", tdList.size());
		json.put("add", add.size());
		json.put("save", save.size());
		json.put("A", A.size());
		json.put("B", B.size());
		json.put("C", C.size());
		json.put("table", arrayLists);
		return json;
	}

	private JSONObject getStatistics(int year) {
		//获取到所有的数据
		//商机
		List<String> sjList = this.getBaseMapper().getSJList(year);
		//入库
		List<String> rkList = this.getBaseMapper().getRkList(year);
		//存量
//		List<String> clList = this.getBaseMapper().getCLList(year);
		//通道
		List<String> tdList = this.getBaseMapper().getTDList(year, PMPConstant.TABLE_TD);
		String str = "(\"";
		str += sjList.stream().collect(Collectors.joining("\",\""));
		//当年数据和存量数据
//		str += "\",\"";
//		str += clList.stream().collect(Collectors.joining("\",\""));
		str += "\")";
		List<String> add = this.getBaseMapper().getKeyCount("xmlx", "新增", str);
		List<String> save = this.getBaseMapper().getKeyCount("xmlx", "存量", str);
		List<String> A = this.getBaseMapper().getKeyCount("xmdj", "A", str);
		List<String> B = this.getBaseMapper().getKeyCount("xmdj", "B", str);
		List<String> C = this.getBaseMapper().getKeyCount("xmdj", "C", str);


		List<JSONObject> listJson = this.getBaseMapper().getRkListByMoney(str);
		ArrayList<String> list = new ArrayList<>();
		list.add("");
		list.add("新增项目");
		list.add("存量项目");
		list.add("预计落地金额（新增）");
		list.add("预计营收（新增、存量））");
		list.add("预计回款（新增、存量）");

		Integer addNum = 0;
		Integer saveNum = 0;
		double yjldNum = 0;
		double yjysNum = 0;
		double yjhkNum = 0;
		for (JSONObject jsonObject : listJson) {
			String xmlx = jsonObject.getOrDefault("xmlx", "新增").toString();
			String yjje = jsonObject.getOrDefault("yjje", "0").toString();
			String yjld = jsonObject.getOrDefault("yjldje", "0").toString();
			String yjys = jsonObject.getOrDefault("yjys", "0").toString();
			String yjhk = jsonObject.getOrDefault("yjhk", "0").toString();

			yjld = "".equals(yjld) ? "0" : yjld;
			yjys = "".equals(yjys) ? "0" : yjys;
			yjhk = "".equals(yjhk) ? "0" : yjhk;
			//新增项目需要统数据，存量项目不用
			if ("新增".equals(xmlx)) {
				addNum += 1;
				yjldNum += Double.valueOf(yjld);
				yjysNum += Double.valueOf(yjys);
				yjhkNum += Double.valueOf(yjhk);
			} else {
				saveNum += 1;
			}
		}
		ArrayList<String> list1 = new ArrayList<>();
		list1.add("全量");
		list1.add(String.valueOf(addNum));
		list1.add(String.valueOf(saveNum));
		list1.add(String.format("%.2f", yjldNum));
		list1.add(String.format("%.2f", yjysNum));
		list1.add(String.format("%.2f", yjhkNum));

		Integer aAdd = 0;
		Integer bAdd = 0;
		Integer cAdd = 0;
		Integer aSave = 0;
		Integer bSave = 0;
		Integer cSave = 0;
		double aYjld = 0;
		double bYjld = 0;
		double cYjld = 0;
		double aYjys = 0;
		double bYjys = 0;
		double cYjys = 0;
		double aYjhk = 0;
		double bYjhk = 0;
		double cYjhk = 0;
		listJson = this.getBaseMapper().getRkListByMoney(str);
		for (JSONObject jsonObject : listJson) {
			String xmlx = jsonObject.getOrDefault("xmlx", "新增").toString();
			String yjje = jsonObject.getOrDefault("yjje", "0").toString();
			String yjld = jsonObject.getOrDefault("yjldje", "0").toString();
			String yjys = jsonObject.getOrDefault("yjys", "0").toString();
			String yjhk = jsonObject.getOrDefault("yjhk", "0").toString();
			String xmdj = jsonObject.getOrDefault("xmdj", "A").toString();
			yjje = "".equals(yjje) ? "0" : yjje;
			yjld = "".equals(yjld) ? "0" : yjld;
			yjys = "".equals(yjys) ? "0" : yjys;
			yjhk = "".equals(yjhk) ? "0" : yjhk;
			xmdj = "".equals(xmdj) ? "0" : xmdj;
			switch (xmdj) {
				case "A":

					if ("新增".equals(xmlx)) {
						aAdd += 1;
						aYjys += Double.valueOf(yjys);
						aYjhk += Double.valueOf(yjhk);
						aYjld += Double.valueOf(yjld);
					} else {
						aSave += 1;
					}
					break;
				case "B":
					if ("新增".equals(xmlx)) {
						bAdd += 1;
						bYjys += Double.valueOf(yjys);
						bYjhk += Double.valueOf(yjhk);
						bYjld += Double.valueOf(yjld);
					} else {
						bSave += 1;
					}
					break;
				case "C":
					if ("新增".equals(xmlx)) {
						cAdd += 1;
						cYjys += Double.valueOf(yjys);
						cYjhk += Double.valueOf(yjhk);
						cYjld += Double.valueOf(yjld);
					} else {
						cSave += 1;
					}
					break;
			}
		}
		ArrayList<String> list2 = new ArrayList<>();
		list2.add("A类");
		list2.add(String.valueOf(aAdd));
		list2.add(String.valueOf(aSave));
		list2.add(String.format("%.2f", aYjld));
		list2.add(String.format("%.2f", aYjys));
		list2.add(String.format("%.2f", aYjhk));
		ArrayList<String> list3 = new ArrayList<>();
		list3.add("B类");
		list3.add(String.valueOf(bAdd));
		list3.add(String.valueOf(bSave));
		list3.add(String.format("%.2f", bYjld));
		list3.add(String.format("%.2f", bYjys));
		list3.add(String.format("%.2f", bYjhk));
		ArrayList<String> list4 = new ArrayList<>();
		list4.add("C类");
		list4.add(String.valueOf(cAdd));
		list4.add(String.valueOf(cSave));
		list4.add(String.format("%.2f", cYjld));
		list4.add(String.format("%.2f", cYjys));
		list4.add(String.format("%.2f", cYjhk));
		ArrayList<ArrayList> arrayLists = new ArrayList<>();
		arrayLists.add(list);
		arrayLists.add(list1);
		arrayLists.add(list2);
		arrayLists.add(list3);
		arrayLists.add(list4);
		JSONObject json = new JSONObject();
		json.put("sj", sjList.size());
		json.put("rk", rkList.size());
		json.put("td", tdList.size());
		json.put("add", add.size());
		json.put("save", save.size());
		json.put("A", A.size());
		json.put("B", B.size());
		json.put("C", C.size());
		json.put("table", arrayLists);
		return json;
	}

	private JSONObject getDataAnalyse(String deptName, int year) {
		//获取到商机所有的数据
		List<String> list = yyDataInfoService.listByYear(year, PMPConstant.TABLE_SJ);
		String str = "(\"";
		str += list.stream().collect(Collectors.joining("\",\""));
		str += "\")";
		//获取当前年份所有数据中属于本部门的数据
		List<String> list1 = yyDataInfoService.yearListByDepart(deptName, str);
		String newStr = "(\"";
		newStr += list1.stream().collect(Collectors.joining("\",\""));
		newStr += "\")";
		//todo判断
		double yjje = this.getBaseMapper().getCountMoney(PMPConstant.KEY_YJ, newStr);//预计金额
		double yjld = this.getBaseMapper().getCountMoney(PMPConstant.KEY_YJLD, newStr);//预计落地
		double yjys = this.getBaseMapper().getCountMoney(PMPConstant.KEY_YJYS, newStr);//预计营收
		double yjhk = this.getBaseMapper().getCountMoney(PMPConstant.KEY_YJHK, newStr);//预计回款


		double sjys = this.getBaseMapper().getCountYearByFlowIdByDeptName(deptName, PMPConstant.KEY_TABLE_SJYS, PMPConstant.KEY_TIME_SJYS, year);//已确认营收
		double sjld = this.getBaseMapper().getCountYearByFlowIdByDeptName(deptName, PMPConstant.KEY_SJLD, PMPConstant.KEY_TIME_SJ, year);//实际落地金额
		double sjhk = this.getBaseMapper().getCountYearByFlowIdByDeptName(deptName, PMPConstant.KEY_TABLE_SJHK, PMPConstant.KEY_TIME_SJHK, year);//实际回款

		String basicStr = "";
		ArrayList<String> keyList = new ArrayList<>();
		keyList.add(PMPConstant.KEY_YJ);
//		keyList.add(PMPConstant.KEY_SJ);
		keyList.add(PMPConstant.KEY_YJLD);
		keyList.add(PMPConstant.KEY_SJLD);
		keyList.add(PMPConstant.KEY_YJYS);
		keyList.add(PMPConstant.KEY_SJYS);
		keyList.add(PMPConstant.KEY_YJHK);
		keyList.add(PMPConstant.KEY_SJHK);
		//加一个归口部门
		keyList.add("gkbm");
		//加一个项目类型，获取增量存量
		keyList.add("xmlx");

		for (String jsonKey : keyList) {
			basicStr += "MAX(IF(json_key = \"" + jsonKey + "\", json_val, NULL)) AS \"" + jsonKey + "\",";
		}
		basicStr = basicStr.substring(0, basicStr.length() - 1);
		//获取所有当年数据属于本部门的数据
		List<String> listByDepart = yyDataInfoService.ListByDepart(deptName, year);
		String departStr = "(\"";
		departStr += listByDepart.stream().collect(Collectors.joining("\",\""));
		departStr += "\")";
		List<JSONObject> jsonList = this.getBaseMapper().getCountList(basicStr, departStr);
		//新增
		HashMap<String, String> yjysAddMap = new HashMap<>();
		HashMap<String, String> sjysAddMap = new HashMap<>();
		HashMap<String, String> yjhkAddMap = new HashMap<>();
		HashMap<String, String> sjhkAddMap = new HashMap<>();
		//存量
		HashMap<String, String> yjysSaveMap = new HashMap<>();
		HashMap<String, String> sjysSaveMap = new HashMap<>();
		HashMap<String, String> yjhkSaveMap = new HashMap<>();
		HashMap<String, String> sjhkSaveMap = new HashMap<>();

		HashMap<String, String> sjhkMap = new HashMap<>();
		HashMap<String, String> sjysMap = new HashMap<>();
		List<String> deptList = this.getBaseMapper().getDeptCountList(departStr);
		deptList.forEach(x -> {
			yjysAddMap.put(x, "0");
			sjysAddMap.put(x, "0");
			yjhkAddMap.put(x, "0");
			sjhkAddMap.put(x, "0");
			yjysSaveMap.put(x, "0");
			sjysSaveMap.put(x, "0");
			yjhkSaveMap.put(x, "0");
			sjhkSaveMap.put(x, "0");
			sjhkMap.put(x, "0");
			sjysMap.put(x, "0");
		});
		for (JSONObject jsonObject : jsonList) {
			if (jsonObject == null) {
				continue;
			}
			String businessKey = jsonObject.getOrDefault("business_key", "").toString();
			String yjysStr = jsonObject.getOrDefault("yjys", "0").toString();
			String sjysStr = jsonObject.getOrDefault("sjys", "0").toString();
			String yjhkStr = jsonObject.getOrDefault("yjhk", "0").toString();
			String sjhkStr = jsonObject.getOrDefault("sjhk", "0").toString();
			Double yjysjeNum = Double.valueOf(yjysStr.equals("") ? "0" : yjysStr);
			Double sjysjeNum = Double.valueOf(sjysStr.equals("") ? "0" : sjysStr);
			Double yjhkjeNum = Double.valueOf(yjhkStr.equals("") ? "0" : yjhkStr);
			Double sjhkjeNum = Double.valueOf(sjhkStr.equals("") ? "0" : sjhkStr);
			//归口部门
			String departName = jsonObject.getOrDefault("gkbm", "其他").toString();
			//项目类型
			String type = jsonObject.getOrDefault("xmlx", "新增").toString();

			//新增-存量

			if ("新增".equals(type)) {
				Double yjysASNum = Double.valueOf(yjysAddMap.get(departName));
				if (yjysjeNum != 0.0) {
					yjysAddMap.put(departName, String.format("%.2f", yjysjeNum + yjysASNum));
				}


				Double yjhkASNum = Double.valueOf(yjhkAddMap.get(departName));
				if (yjhkjeNum != 0.0) {
					yjhkAddMap.put(departName, String.format("%.2f", yjhkjeNum + yjhkASNum));
				}
				/*Double sjysASNum = Double.valueOf(sjysAddMap.get(departName));
				if (sjysjeNum != 0.0) {
					sjysAddMap.put(departName,  String.format("%.2f", sjysjeNum + sjysASNum));
				}
				Double sjhkASNum = Double.valueOf(sjhkAddMap.get(departName));
				if (sjhkjeNum != 0.0) {
					sjhkAddMap.put(departName,  String.format("%.2f", sjhkjeNum + sjhkASNum));
				}*/
			} else {


				Double yjysASNum = Double.valueOf(yjysSaveMap.get(departName));
				if (yjysjeNum != 0.0) {
					yjysSaveMap.put(departName, String.format("%.2f", yjysjeNum + yjysASNum));
				}
				Double yjhkASNum = Double.valueOf(yjhkSaveMap.get(departName));
				if (yjhkjeNum != 0.0) {
					yjhkSaveMap.put(departName, String.format("%.2f", yjhkjeNum + yjhkASNum));
				}

				//实际回款
				/*Double sjhkTable=this.getBaseMapper().getTableCountByKey(businessKey,"hksj","hkje_table",year,"sjhk");
				Double sjhkASNum = Double.valueOf(sjhkSaveMap.get(departName));
				if (sjhkTable != 0.0) {
					sjhkSaveMap.put(departName,String.format("%.2f", sjhkTable + sjhkASNum) );
				}*/


				//已确认营收
				/*Double qrysTable=this.getBaseMapper().getTableCountByKey(businessKey,"ysqrsj","ysje",year,"qrys");
				Double sjysASNum = Double.valueOf(sjysSaveMap.get(departName));
				if (sjysjeNum != 0.0) {
					sjysSaveMap.put(departName,  String.format("%.2f", qrysTable + sjysASNum));
				}*/
			}
		}

		//实际回款和已确认营收是根据表单中的日期来统计得到的
		//实际回款符合的表格数据
		List<String> sjhkFlowList = this.getBaseMapper().listByFlowByDePartName(PMPConstant.KEY_TIME_SJHK, year, deptName);
		sjhkFlowList.forEach(x -> {

			JSONObject json = this.getBaseMapper().getBusinessKey(PMPConstant.KEY_TABLE_SJHK, x);
			String businessKey = json.getOrDefault("business_key", "").toString();
			String json_val = json.getOrDefault("json_val", "").toString();
			JSONObject json1 = this.getBaseMapper().getInfo(businessKey);
			String xmlx = json1.getOrDefault("xmlx", "").toString();
			String departName = json1.getOrDefault("gkbm", "").toString();
			Double sjhkjeNum = Double.valueOf(json_val.equals("") ? "0" : json_val);
			//新增-存量
			if ("新增".equals(xmlx)) {

				Double sjhkASNum = Double.valueOf(sjhkAddMap.get(departName));
				if (sjhkASNum == null && sjhkjeNum != 0) {
					sjhkAddMap.put(departName, String.format("%.2f", sjhkjeNum));
				} else if (sjhkASNum != null && sjhkjeNum != 0) {
					sjhkAddMap.put(departName, String.format("%.2f", sjhkjeNum + sjhkASNum));
				}

				Double sjhkNum = Double.valueOf(sjhkMap.get(departName) == null ? "0" : sjhkMap.get(departName));
				if (sjhkNum == null && sjhkjeNum != 0) {
					sjhkMap.put(departName, String.format("%.2f", sjhkjeNum));
				} else if (sjhkNum != null && sjhkjeNum != 0) {
					sjhkMap.put(departName, String.format("%.2f", (sjhkjeNum + sjhkNum)));
				}


			} else {


				//实际回款
				Double sjhkTable = this.getBaseMapper().getTableCountByKey(businessKey, "hksj", "hkje_table", year, "sjhk");
				Double sjhkASNum = Double.valueOf(sjhkSaveMap.get(departName));
				if (sjhkTable != 0.0) {
					sjhkSaveMap.put(departName, String.format("%.2f", sjhkTable + sjhkASNum));
				}

			}
		});

		//已确认营收
		List<String> yqrysFlowList = this.getBaseMapper().listByFlowByDePartName(PMPConstant.KEY_TIME_SJYS, year, deptName);
		yqrysFlowList.forEach(x -> {

			JSONObject json = this.getBaseMapper().getBusinessKey(PMPConstant.KEY_TABLE_SJYS, x);
			String businessKey = json.getOrDefault("business_key", "").toString();
			String json_val = json.getOrDefault("json_val", "").toString();
			JSONObject json1 = this.getBaseMapper().getInfo(businessKey);
			String xmlx = json1.getOrDefault("xmlx", "").toString();
			String departName = json1.getOrDefault("gkbm", "").toString();
			Double sjysjeNum = Double.valueOf(json_val.equals("") ? "0" : json_val);
			//新增-存量
			if ("新增".equals(xmlx)) {

				Double sjysASNum = Double.valueOf(sjysAddMap.get(departName));
				if (sjysASNum == null && sjysjeNum != 0) {
					sjysAddMap.put(departName, String.format("%.2f", sjysjeNum));
				} else if (sjysASNum != null && sjysjeNum != 0) {
					sjysAddMap.put(departName, String.format("%.2f", sjysjeNum + sjysASNum));
				}
				Double sjysNum = Double.valueOf(sjysMap.get(departName) == null ? "0" : sjysMap.get(departName));
				if (sjysNum == null && sjysjeNum != 0) {
					sjysMap.put(departName, String.format("%.2f", sjysjeNum));
				} else if (sjysNum != null && sjysjeNum != 0) {
					sjysMap.put(departName, String.format("%.2f", sjysjeNum + sjysNum));
				}


			} else {


				//已确认营收
				Double qrysTable = this.getBaseMapper().getTableCountByKey(businessKey, "ysqrsj", "ysje", year, "qrys");
				Double sjysASNum = Double.valueOf(sjysSaveMap.get(departName));
				if (sjysjeNum != 0.0) {
					sjysSaveMap.put(departName, String.format("%.2f", qrysTable + sjysASNum));
				}

			}
		});

		JSONObject jsonObject1 = new JSONObject();
		jsonObject1.put("tdList", 0);
		jsonObject1.put("tdMoney", "0");
		jsonObject1.put("tdLdje", "0");
		jsonObject1.put("yjje", yjje);
//		jsonObject1.put("sjje", sjje);
		jsonObject1.put("yjld", yjld);
		jsonObject1.put("sjld", sjld);
		jsonObject1.put("yjys", yjys);
		jsonObject1.put("sjys", sjys);
		jsonObject1.put("yjhk", yjhk);
		jsonObject1.put("sjhk", sjhk);
		JSONObject jsonObject2 = new JSONObject();
		jsonObject2.put("yjysAddMap", yjysAddMap);
		jsonObject2.put("sjysAddMap", sjysAddMap);
		jsonObject2.put("yjhkAddMap", yjhkAddMap);
		jsonObject2.put("sjhkAddMap", sjhkAddMap);
		jsonObject2.put("yjysSaveMap", yjysSaveMap);
		jsonObject2.put("sjysSaveMap", sjysSaveMap);
		jsonObject2.put("yjhkSaveMap", yjhkSaveMap);
		jsonObject2.put("sjhkSaveMap", sjhkSaveMap);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("count", jsonObject1);
		jsonObject.put("addSave", jsonObject2);
		jsonObject.put("statistics", "statistics");
		return jsonObject;
	}

	private JSONObject AllDataAnalyse(int year) {
		//获取到商机所有的数据
		List<String> list = yyDataInfoService.listByYear(year, PMPConstant.TABLE_SJ);
		String str = "(\"";
		str += list.stream().collect(Collectors.joining("\",\""));
		str += "\")";


		//预计--根据当前时间戳统计
		//实际回款--根据表格中的数据计算
		double yjhk = this.getBaseMapper().getCountMoney(PMPConstant.KEY_YJHK, str);//预计回款
		//根据表格中回款时间统计实际回款金额-已确认营收
		double yjys = this.getBaseMapper().getCountMoney(PMPConstant.KEY_YJYS, str);//预计营收
		double yjld = this.getBaseMapper().getCountMoney(PMPConstant.KEY_YJLD, str);//预计落地金额

		double sjys = this.getBaseMapper().getCountYearByFlowId(PMPConstant.KEY_TABLE_SJYS, PMPConstant.KEY_TIME_SJYS, year);//已确认营收
		double sjld = this.getBaseMapper().getCountYear(PMPConstant.KEY_SJLD, PMPConstant.KEY_TIME_SJ, year);//实际落地金额
		double sjhk = this.getBaseMapper().getCountYearByFlowId(PMPConstant.KEY_TABLE_SJHK, PMPConstant.KEY_TIME_SJHK, year);//实际回款


		//通道项目情况
		List<String> tdList = yyDataInfoService.tdYearList(year);
		String tdStr = "(\"";
		tdStr += tdList.stream().collect(Collectors.joining("\",\""));
		tdStr += "\")";
		double tdMoney = this.getBaseMapper().getCountMoney(PMPConstant.KEY_TDJE, tdStr);
		double tdLdje = this.getBaseMapper().getCountMoney(PMPConstant.KEY_TDLDJE, tdStr);

		String basicStr = "";
		ArrayList<String> keyList = new ArrayList<>();
//		keyList.add(PMPConstant.KEY_YJ);
//		keyList.add(PMPConstant.KEY_SJ);
		keyList.add(PMPConstant.KEY_YJLD);
		keyList.add(PMPConstant.KEY_SJLD);
		keyList.add(PMPConstant.KEY_YJYS);
		keyList.add(PMPConstant.KEY_YJHK);
//		keyList.add(PMPConstant.KEY_SJYS);
//		keyList.add(PMPConstant.KEY_SJHK);
		//加一个归口部门
		keyList.add("gkbm");
		//加一个项目类型，获取增量存量
		keyList.add("xmlx");

		for (String jsonKey : keyList) {
			basicStr += "MAX(IF(json_key = \"" + jsonKey + "\", json_val, NULL)) AS \"" + jsonKey + "\",";
		}
		basicStr = basicStr.substring(0, basicStr.length() - 1);
		List<JSONObject> jsonList = this.getBaseMapper().getCountList(basicStr, str);
		jsonList.remove(null);
		List<String> deptList = this.getBaseMapper().getDeptCountList(str);
//		HashMap<String, String> yjMap = new HashMap<>();
//		HashMap<String, String> sjMap = new HashMap<>();
		HashMap<String, String> yjldMap = new HashMap<>();
		HashMap<String, String> sjldMap = new HashMap<>();
		HashMap<String, String> yjysMap = new HashMap<>();
		HashMap<String, String> sjysMap = new HashMap<>();
		HashMap<String, String> yjhkMap = new HashMap<>();
		HashMap<String, String> sjhkMap = new HashMap<>();

		//新增
		HashMap<String, String> yjysAddMap = new HashMap<>();
		HashMap<String, String> yjhkAddMap = new HashMap<>();

		//存量
		HashMap<String, String> yjysSaveMap = new HashMap<>();
		HashMap<String, String> yjhkSaveMap = new HashMap<>();

		HashMap<String, String> sjysAddMap = new HashMap<>();
		HashMap<String, String> sjhkAddMap = new HashMap<>();
		HashMap<String, String> sjysSaveMap = new HashMap<>();
		HashMap<String, String> sjhkSaveMap = new HashMap<>();
		deptList.forEach(x -> {
			yjysAddMap.put(x, "0");
			sjysAddMap.put(x, "0");
			yjhkAddMap.put(x, "0");
			sjhkAddMap.put(x, "0");
			yjysSaveMap.put(x, "0");
			sjysSaveMap.put(x, "0");
			yjhkSaveMap.put(x, "0");
			sjhkSaveMap.put(x, "0");
		});
		for (JSONObject jsonObject : jsonList) {
			if (jsonObject == null) {
				continue;
			}
			String businessKey = jsonObject.getOrDefault("business_key", "").toString();
			String yjjeStr = jsonObject.getOrDefault("yjje", "0").toString();
			String sjjeStr = jsonObject.getOrDefault("sjje", "0").toString();
			String yjldjeStr = jsonObject.getOrDefault("yjldje", "0").toString();
			String sjldjeStr = jsonObject.getOrDefault("sjldje", "0").toString();
			String yjysStr = jsonObject.getOrDefault("yjys", "0").toString();
//			String sjysStr = jsonObject.getOrDefault("sjys", "0").toString();
			String yjhkStr = jsonObject.getOrDefault("yjhk", "0").toString();
//			String sjhkStr = jsonObject.getOrDefault("sjhk", "0").toString();
			Double yjjeNum = Double.valueOf(yjjeStr.equals("") ? "0" : yjjeStr);
			Double sjjeNum = Double.valueOf(sjjeStr.equals("") ? "0" : sjjeStr);
			Double yjldjeNum = Double.valueOf(yjldjeStr.equals("") ? "0" : yjldjeStr);
			Double sjldjeNum = Double.valueOf(sjldjeStr.equals("") ? "0" : sjldjeStr);
			Double yjysjeNum = Double.valueOf(yjysStr.equals("") ? "0" : yjysStr);
//			Double sjysjeNum = Double.valueOf(sjysStr.equals("") ? "0" : sjysStr);
			Double yjhkjeNum = Double.valueOf(yjhkStr.equals("") ? "0" : yjhkStr);
//			Double sjhkjeNum = Double.valueOf(sjhkStr.equals("") ? "0" : sjhkStr);
			//归口部门
			String departName = jsonObject.getOrDefault("gkbm", "其他").toString();
			//项目类型
			String type = jsonObject.getOrDefault("xmlx", "新增").toString();

			//新增-存量
			if ("新增".equals(type)) {
				Double yjysASNum = Double.valueOf(yjysAddMap.get(departName));
				if (yjysASNum == null && yjysjeNum != 0) {
					yjysAddMap.put(departName, String.format("%.2f", yjysjeNum));
				} else if (yjysASNum != null && yjysjeNum != 0) {
					yjysAddMap.put(departName, String.format("%.2f", yjysjeNum + yjysASNum));
				}


				Double yjhkASNum = Double.valueOf(yjhkAddMap.get(departName));
				if (yjhkASNum == null && yjhkjeNum != 0) {
					yjhkAddMap.put(departName, String.format("%.2f", yjhkjeNum));
				} else if (yjhkASNum != null && yjhkjeNum != 0) {
					yjhkAddMap.put(departName, String.format("%.2f", yjhkjeNum + yjhkASNum));
				}


				Double yjldNum = Double.valueOf(yjldMap.get(departName) == null ? "0" : yjldMap.get(departName));
				if (yjldNum == null && yjldjeNum != 0) {
					yjldMap.put(departName, String.format("%.2f", yjldjeNum));
				} else if (yjldNum != null && yjldjeNum != 0) {
					yjldMap.put(departName, String.format("%.2f", yjldjeNum + yjldNum));
				}

				Double sjldNum = Double.valueOf(sjldMap.get(departName) == null ? "0" : sjldMap.get(departName));
				if (sjldNum == null && sjldjeNum != 0) {
					sjldMap.put(departName, String.format("%.2f", sjldjeNum));
				} else if (sjldNum != null && sjldjeNum != 0) {
					sjldMap.put(departName, String.format("%.2f", sjldjeNum + sjldNum));
				}

				Double yjysNum = Double.valueOf(yjysMap.get(departName) == null ? "0" : yjysMap.get(departName));
				if (yjysNum == null && yjysjeNum != 0) {
					yjysMap.put(departName, String.format("%.2f", yjysjeNum));
				} else if (yjysNum != null && yjysjeNum != 0) {
					yjysMap.put(departName, String.format("%.2f", yjysjeNum + yjysNum));
				}
/*Double sjysASNum = Double.valueOf(sjysAddMap.get(departName));
				if (sjysASNum == null && sjysjeNum != 0) {
					sjysAddMap.put(departName, String.format("%.2f", sjysjeNum));
				} else if (sjysASNum != null && sjysjeNum != 0) {
					sjysAddMap.put(departName,String.format("%.2f",  sjysjeNum + sjysASNum));
				}*/
				/*Double sjysNum = Double.valueOf(sjysMap.get(departName)==null? "0" :sjysMap.get(departName));
				if (sjysNum == null && sjysjeNum != 0) {
					sjysMap.put(departName,  String.format("%.2f", sjysjeNum));
				} else if (sjysNum != null && sjysjeNum != 0) {
					sjysMap.put(departName,  String.format("%.2f", sjysjeNum + sjysNum));
				}*/

				Double yjhkNum = Double.valueOf(yjhkMap.get(departName) == null ? "0" : yjhkMap.get(departName));
				if (yjhkNum == null && yjhkjeNum != 0) {
					yjhkMap.put(departName, String.format("%.2f", yjhkjeNum));
				} else if (yjhkNum != null && yjhkjeNum != 0) {
					yjhkMap.put(departName, String.format("%.2f", yjhkjeNum + yjhkNum));
				}
	/*Double sjhkASNum = Double.valueOf(sjhkAddMap.get(departName));
				if (sjhkASNum == null && sjhkjeNum != 0) {
					sjhkAddMap.put(departName, String.format("%.2f", sjhkjeNum));
				} else if (sjhkASNum != null && sjhkjeNum != 0) {
					sjhkAddMap.put(departName,String.format("%.2f", sjhkjeNum + sjhkASNum) );
				}*/

				/*Double sjhkNum = Double.valueOf(sjhkMap.get(departName)==null? "0" :sjhkMap.get(departName));
				if (sjhkNum == null && sjhkjeNum != 0) {
					sjhkMap.put(departName,  String.format("%.2f", sjhkjeNum));
				} else if (sjhkNum != null && sjhkjeNum != 0) {
					sjhkMap.put(departName, String.format("%.2f", (sjhkjeNum + sjhkNum)) );
				}*/
			} else {


				//预计营收
				Double yjysASNum = Double.valueOf(yjysSaveMap.get(departName));
				if (yjysjeNum != 0.0) {
					yjysSaveMap.put(departName, String.format("%.2f", yjysjeNum + yjysASNum));
				}

				Double yjhkASNum = Double.valueOf(yjhkSaveMap.get(departName));
				if (yjhkjeNum != 0.0) {
					yjhkSaveMap.put(departName, String.format("%.2f", yjhkjeNum + yjhkASNum));
				}

				//实际回款
				/*Double sjhkTable=this.getBaseMapper().getTableCountByKey(businessKey,"hksj","hkje_table",year,"sjhk");
				Double sjhkASNum = Double.valueOf(sjhkSaveMap.get(departName));
				if (sjhkTable != 0.0) {
					sjhkSaveMap.put(departName,String.format("%.2f", sjhkTable + sjhkASNum) );
				}*/

				//已确认营收
			/*	Double qrysTable=this.getBaseMapper().getTableCountByKey(businessKey,"ysqrsj","ysje",year,"qrys");
				Double sjysASNum = Double.valueOf(sjysSaveMap.get(departName));
				if (sjysjeNum != 0.0) {
					sjysSaveMap.put(departName, String.format("%.2f", qrysTable + sjysASNum));
				}*/

			}


		}

		//实际回款和已确认营收是根据表单中的日期来统计得到的
		//实际回款符合的表格数据
		List<String> sjhkFlowList = this.getBaseMapper().listByFlow(PMPConstant.KEY_TIME_SJHK, year);
		sjhkFlowList.forEach(x -> {

			JSONObject json = this.getBaseMapper().getBusinessKey(PMPConstant.KEY_TABLE_SJHK, x);
			String businessKey = json.getOrDefault("business_key", "").toString();
			String json_val = json.getOrDefault("json_val", "").toString();
			JSONObject json1 = this.getBaseMapper().getInfo(businessKey);
			String xmlx = json1.getOrDefault("xmlx", "").toString();
			String departName = json1.getOrDefault("gkbm", "").toString();
			Double sjhkjeNum = Double.valueOf(json_val.equals("") ? "0" : json_val);
			//新增-存量
			if ("新增".equals(xmlx)) {

				Double sjhkASNum = Double.valueOf(sjhkAddMap.get(departName));
				if (sjhkASNum == null && sjhkjeNum != 0) {
					sjhkAddMap.put(departName, String.format("%.2f", sjhkjeNum));
				} else if (sjhkASNum != null && sjhkjeNum != 0) {
					sjhkAddMap.put(departName, String.format("%.2f", sjhkjeNum + sjhkASNum));
				}

				Double sjhkNum = Double.valueOf(sjhkMap.get(departName) == null ? "0" : sjhkMap.get(departName));
				if (sjhkNum == null && sjhkjeNum != 0) {
					sjhkMap.put(departName, String.format("%.2f", sjhkjeNum));
				} else if (sjhkNum != null && sjhkjeNum != 0) {
					sjhkMap.put(departName, String.format("%.2f", (sjhkjeNum + sjhkNum)));
				}


			} else {


				//实际回款
				Double sjhkTable = this.getBaseMapper().getTableCountByKey(businessKey, "hksj", "hkje_table", year, "sjhk");
				Double sjhkASNum = Double.valueOf(sjhkSaveMap.get(departName));
				if (sjhkTable != 0.0) {
					sjhkSaveMap.put(departName, String.format("%.2f", sjhkTable + sjhkASNum));
				}

			}
		});

		//已确认营收
		List<String> yqrysFlowList = this.getBaseMapper().listByFlow(PMPConstant.KEY_TIME_SJYS, year);
		yqrysFlowList.forEach(x -> {

			JSONObject json = this.getBaseMapper().getBusinessKey(PMPConstant.KEY_TABLE_SJYS, x);
			String businessKey = json.getOrDefault("business_key", "").toString();
			String json_val = json.getOrDefault("json_val", "").toString();
			JSONObject json1 = this.getBaseMapper().getInfo(businessKey);
			String xmlx = json1.getOrDefault("xmlx", "").toString();
			String departName = json1.getOrDefault("gkbm", "").toString();
			Double sjysjeNum = Double.valueOf(json_val.equals("") ? "0" : json_val);
			//新增-存量
			if ("新增".equals(xmlx)) {

				Double sjysASNum = Double.valueOf(sjysAddMap.get(departName));
				if (sjysASNum == null && sjysjeNum != 0) {
					sjysAddMap.put(departName, String.format("%.2f", sjysjeNum));
				} else if (sjysASNum != null && sjysjeNum != 0) {
					sjysAddMap.put(departName, String.format("%.2f", sjysjeNum + sjysASNum));
				}
				Double sjysNum = Double.valueOf(sjysMap.get(departName) == null ? "0" : sjysMap.get(departName));
				if (sjysNum == null && sjysjeNum != 0) {
					sjysMap.put(departName, String.format("%.2f", sjysjeNum));
				} else if (sjysNum != null && sjysjeNum != 0) {
					sjysMap.put(departName, String.format("%.2f", sjysjeNum + sjysNum));
				}


			} else {


				//已确认营收
				Double qrysTable = this.getBaseMapper().getTableCountByKey(businessKey, "ysqrsj", "ysje", year, "qrys");
				Double sjysASNum = Double.valueOf(sjysSaveMap.get(departName));
				if (sjysjeNum != 0.0) {
					sjysSaveMap.put(departName, String.format("%.2f", qrysTable + sjysASNum));
				}

			}
		});


		JSONObject jsonObject1 = new JSONObject();
		jsonObject1.put("yjld", String.format("%.2f", yjld));
		jsonObject1.put("sjld", String.format("%.2f", sjld));

		jsonObject1.put("yjys", String.format("%.2f", yjys));
		jsonObject1.put("sjys", String.format("%.2f", sjys));

		jsonObject1.put("yjhk", String.format("%.2f", yjhk));
		jsonObject1.put("sjhk", String.format("%.2f", sjhk));


		jsonObject1.put("tdList", tdList.size());
		jsonObject1.put("tdMoney", String.format("%.2f", tdMoney));
		jsonObject1.put("tdLdje", String.format("%.2f", tdLdje));
		JSONObject jsonObject2 = new JSONObject();
//		jsonObject2.put("yjMap",yjMap);
//		jsonObject2.put("sjMap", sjMap);
		jsonObject2.put("yjldMap", yjldMap);
		jsonObject2.put("sjldMap", sjldMap);
		jsonObject2.put("yjysMap", yjysMap);
		jsonObject2.put("sjysMap", sjysMap);
		jsonObject2.put("yjhkMap", yjhkMap);
		jsonObject2.put("sjhkMap", sjhkMap);

		JSONObject jsonObject3 = new JSONObject();
		jsonObject3.put("yjysAddMap", yjysAddMap);
		jsonObject3.put("sjysAddMap", sjysAddMap);
		jsonObject3.put("yjhkAddMap", yjhkAddMap);
		jsonObject3.put("sjhkAddMap", sjhkAddMap);
		jsonObject3.put("yjysSaveMap", yjysSaveMap);
		jsonObject3.put("sjysSaveMap", sjysSaveMap);
		jsonObject3.put("yjhkSaveMap", yjhkSaveMap);
		jsonObject3.put("sjhkSaveMap", sjhkSaveMap);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("count", jsonObject1);
		jsonObject.put("countList", jsonObject2);
		jsonObject.put("addSave", jsonObject3);
		return jsonObject;

	}


	/**
	 * 员工查询数据
	 *
	 * @return
	 */
	@Override
	public List<String> getFlowList1ByMyKey(String myKey, String getRealName, int pgIndex, int pgSize) {
		return this.getBaseMapper().getFlowList1ByMyKey(myKey, getRealName, pgIndex, pgSize);
	}

	@Override
	public int getFlowList1CountByMyKey(String myKey, String getRealName) {
		return this.getBaseMapper().getFlowList1CountByMyKey(myKey, getRealName);
	}

	@Override
	public List<String> getFlowListByMyKeyStr(String myKey, String deptName, int pgIndex, int pgSize, String str) {
		return this.getBaseMapper().getFlowListByMyKeyStr(myKey, deptName, pgIndex, pgSize, str);
	}

	@Override
	public int getFlowListCountByMyKeyStr(String myKey, String deptName, String str) {
		return this.getBaseMapper().getFlowListCountByMyKeyStr(myKey, deptName, str);
	}


	@Override
	public List<String> getFlowListByMyKey(String myKey, String deptName, int pgIndex, int pgSize) {
		return this.getBaseMapper().getFlowListByMyKey(myKey, deptName, pgIndex, pgSize);
	}

	@Override
	public int getFlowListCountByMyKey(String myKey, String deptName) {
		return this.getBaseMapper().getFlowListCountByMyKey(myKey, deptName);
	}

	@Override
	public List<String> getFlowListStr(String myKey, String deptName, int pgIndex, int pgSize, String str) {
		return this.getBaseMapper().getFlowListStr(myKey, deptName, pgIndex, pgSize, str);
	}

	@Override
	public int getFlowListCountStr(String myKey, String deptName, String str) {
		return this.getBaseMapper().getFlowListCountStr(myKey, deptName, str);
	}


	/**
	 * 部门老大根据归口部门查询数据
	 *
	 * @return
	 */
	@Override
	public List<String> getFlowList(String myKey, String deptName, int pgIndex, int pgSize) {
		return this.getBaseMapper().getFlowList(myKey, deptName, pgIndex, pgSize);
	}

	@Override
	public int getFlowListCount(String myKey, String deptName) {
		return this.getBaseMapper().getFlowListCount(myKey, deptName);
	}

	@Override
	public List<String> getFlowList1ByName(String myKey, String getRealName, int pgIndex, int pgSize, String str) {
		return this.getBaseMapper().getFlowList1ByName(myKey, getRealName, pgIndex, pgSize, str);
	}

	@Override
	public int getFlowList1CountByName(String myKey, String getRealName, String str) {
		return this.getBaseMapper().getFlowList1CountByName(myKey, getRealName, str);
	}

	@Override
	public void removeByBusinessKey(String flowId) {
		this.remove(new LambdaQueryWrapper<>(BasicLoadEntity.class).eq(BasicLoadEntity::getBusinessKey, flowId));
	}

	/**
	 * 根据flowId查询项目值
	 *
	 * @param flowId
	 * @return
	 */
	@Override
	public String getPmpValue(String key, String flowId) {

		return this.getBaseMapper().getPmpValue(key, flowId);
	}

	@Override
	public String getPmpValueByBus(String keyXmmc, String tableId) {
		return this.getBaseMapper().getPmpValueByBus(keyXmmc, tableId);
	}


	/**
	 * 删除所有含有key的数据
	 *
	 * @param jsonKey
	 */
	@Override
	public void removeByKey(String jsonKey) {
		this.remove(Wrappers.<BasicLoadEntity>lambdaQuery().eq(BasicLoadEntity::getJsonKey, jsonKey));
	}


	/**
	 * 员工查询数据
	 *
	 * @return
	 */
	@Override
	public List<String> getFlowList1(String myKey, String jsonKey, String getRealName, int pgIndex, int pgSize) {
		return this.getBaseMapper().getFlowList1(myKey, jsonKey, getRealName, pgIndex, pgSize);
	}

	@Override
	public int getFlowList1Count(String myKey, String jsonKey, String getRealName) {
		return this.getBaseMapper().getFlowList1Count(myKey, jsonKey, getRealName);
	}




	private List<DemoData> data() {
		List<DemoData> list = ListUtils.newArrayList();
		for (int i = 0; i < 10; i++) {
			DemoData data = new DemoData();
			data.setString("字符串" + i);
			data.setDoubleData(0.56);
			list.add(data);
		}
		return list;
	}

	/**
	 * 根据mykey和flowId查询数据
	 *
	 * @param myKey
	 * @param flowId
	 * @return
	 */
	@Override
	public HashMap<String, Object> getParamData(String myKey, String flowId) {
		DeployFormMappingEntity deployFormMappingEntity = deployFormMappingService.getByMyKey(myKey);

		String externalParameterId = deployFormMappingEntity.getExternalParameterId();
		//获取项目表单配置
		YYExternalParameterEntity externalParameterEntity = yyExternalParameterService.getById(externalParameterId);
		if (ObjectUtil.isEmpty(externalParameterEntity)) {
			throw new RuntimeException("外部参数id错误");
		}
		String place = externalParameterEntity.getPlace();

		HashMap<String, Object> paramMap = new HashMap<>();//存储表头和外部参数
		LinkedHashMap<String, HashMap<String, Object>> map = new LinkedHashMap<>();//存储表头
		List<YYBasicEntity> basicList = yyBasicService.getColumList(place);
		String basicStr = "";
		for (YYBasicEntity yyBasicEntity : basicList) {
			String jsonKey = yyBasicEntity.getJsonKey();
			basicStr += "MAX(IF(json_key = \"" + jsonKey + "\", json_val, NULL)) AS \"" + jsonKey + "\",";
		}
		basicStr = basicStr.substring(0, basicStr.length() - 1);
		//表单数据
		JSONObject paramData = this.getBaseMapper().getParamData1(flowId,basicStr);

//		JSONObject columnData = new JSONObject(true);
		//表格数据暂时不用
		/*String[] placeArr = getStrings(externalParameterEntity.getTableInfo());
		Arrays.stream(placeArr).forEach(x -> {
			List<JSONObject> json = this.getBaseMapper().getColumnData(flowId, x);
			columnData.put(x, json);
		});*/
		paramMap.put("paramData", paramData);
//		paramMap.put("columnData", columnData);
		return paramMap;
	}



	/**
	 * 数据导入
	 *
	 * @param myKey
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean importExcel(String myKey, MultipartFile file) {
		if (!PMPConstant.TABLE_SJ.equals(myKey)) {
			throw new ServiceException("只有商机项目能导入数据");
		}
		Long userId = AuthUtil.getUser().getUserId();
		try {
			List<LinkedHashMap<String, String>> list = EasyExcel.read(file.getInputStream()).sheet(0).doReadSync();
			list.remove(0);//删除表头
			DeployFormMappingEntity deployFormMappingEntity = deployFormMappingService.getByMyKey(myKey);
			String externalParameterId = deployFormMappingEntity.getExternalParameterId();
			if (StringUtil.isEmpty(externalParameterId)) {
				throw new ServiceException("表单配置数据为空");
			}
			YYExternalParameterEntity yyExternalParameterEntity = yyExternalParameterService.getById(externalParameterId);
			String place = yyExternalParameterEntity.getPlace();//基本数据表单
			List<YYBasicEntity> colum = yyBasicService.getColum(place);


			LinkedList<JSONObject> linkedList = new LinkedList<>();
			list.forEach(x -> {
				AtomicInteger index = new AtomicInteger();
				JSONObject jsonObject = new JSONObject(true);
				colum.forEach(y -> {
					if (null == x.getOrDefault(index.get(), "")) {
						return;
					}
					jsonObject.put(y.getJsonKey(), x.getOrDefault(index.get(), ""));
					index.addAndGet(1);
				});
				linkedList.add(jsonObject);

			});
			/**/
			/*for (List<JSONObject> x : list) {

				System.out.println(x);
			}*/
			ArrayList<YYDataInfoEntity> yyDataInfoEntities = new ArrayList<>();
			linkedList.forEach(x -> {
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				YYDataInfoEntity yyDataInfoEntity = new YYDataInfoEntity();
				yyDataInfoEntity.setFlowId(uuid);
				yyDataInfoEntity.setCreator(userId);
				yyDataInfoEntity.setMyKey(myKey);
				yyDataInfoEntity.setStatus(PMPConstant.STATUS_0);
				yyDataInfoEntities.add(yyDataInfoEntity);
				this.add(x, place, uuid);
			});

			return yyDataInfoService.saveBatch(yyDataInfoEntities);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 新数据分析-项目总览
	 * 当时间为空时，默认统计所有数据
	 *
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@Override
	public HashMap<String, Object> newDataAnalyse(String startTime, String endTime) {
		String[] arr = {PMPConstant.TABLE_SJ, PMPConstant.TABLE_RK};
		HashMap<String, Object> map = new HashMap<>();
		for (String myKey : arr) {
			String tableName = "";
			switch (myKey) {
				case PMPConstant.TABLE_SJ:
					tableName = "商机统计";
					break;
				case PMPConstant.TABLE_RK:
					tableName = "入库统计";
					break;
			}
			DataAnalyseVo dataAnalyseVo = new DataAnalyseVo();
			List<String> list = yyDataInfoService.myKeyList(myKey);
			AtomicDouble atomicDouble = new AtomicDouble(0);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			AtomicInteger atomicInteger = new AtomicInteger();
			ArrayList<DataAnalyseInfoVo> dataAnalyseInfoVos = new ArrayList<>();
			list.forEach(x -> {
				DataAnalyseInfoVo dataAnalyseInfoVo = null;
				double yjld = 0.0d;
				String dataStartTime = this.getBaseMapper().getPmpValueByBus(PMPConstant.Key_YJQDSJ, x);//预计签约时间
				String smjd = this.getBaseMapper().getPmpValueByBus(PMPConstant.Key_XMJD, x);//项目阶段
				String yjldje = this.getBaseMapper().getPmpValueByBus(PMPConstant.KEY_YJLD, x);//预计落地金额
				String xmmc = this.getBaseMapper().getPmpValueByBus(PMPConstant.KEY_XMMC, x);//项目名称
				if (StringUtil.isNotBlank(startTime) && StringUtil.isNotBlank(endTime)) {
					if (null == dataStartTime) {
						return;
					}
					try {
						//当预计签约时间小于开始时间或者大于结束时间时跳过
						if (sdf.parse(startTime).compareTo(sdf.parse(dataStartTime)) <= 0 && sdf.parse(endTime).compareTo(sdf.parse(dataStartTime)) >= 0) {
							dataAnalyseInfoVo = new DataAnalyseInfoVo();
							yjld = this.getBaseMapper().getCountMoneyByMyKeyAndBus(PMPConstant.KEY_YJLD, x);//项目预计落地金额
							atomicDouble.addAndGet(yjld);
							atomicInteger.getAndIncrement();
							dataAnalyseInfoVo.setBusinessKey(x);
							dataAnalyseInfoVo.setXmjd(smjd);
							dataAnalyseInfoVo.setYjldje(yjldje);
							dataAnalyseInfoVo.setYjldje(yjldje);
							dataAnalyseInfoVo.setXmmc(xmmc);
							dataAnalyseInfoVo.setMyKey(myKey);
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}
				} else {
					dataAnalyseInfoVo = new DataAnalyseInfoVo();
					yjld = this.getBaseMapper().getCountMoneyByMyKeyAndBus(PMPConstant.KEY_YJLD, x);//项目预计落地金额
					atomicDouble.addAndGet(yjld);
					atomicInteger.getAndIncrement();
					dataAnalyseInfoVo.setBusinessKey(x);
					dataAnalyseInfoVo.setXmjd(smjd);
					dataAnalyseInfoVo.setYjldje(yjldje);
					dataAnalyseInfoVo.setYjldje(yjldje);
					dataAnalyseInfoVo.setXmmc(xmmc);
					dataAnalyseInfoVo.setMyKey(myKey);
				}
				if (!ObjectUtil.isEmpty(dataAnalyseInfoVo)) {
					dataAnalyseInfoVos.add(dataAnalyseInfoVo);
				}

			});
			dataAnalyseVo.setCount(atomicInteger.get());
			dataAnalyseVo.setMoney(atomicDouble.get());
			dataAnalyseVo.setInfo(dataAnalyseInfoVos);
			map.put(tableName, dataAnalyseVo);
		}
		return map;
	}
	/**
	 * 模板导出
	 *
	 * @param myKey
	 * @return
	 */
	@Override
	public String template(String myKey, HttpServletResponse response) {
		String fileName = System.currentTimeMillis() + "";
		switch (myKey) {
			case PMPConstant.TABLE_SJ:
				fileName += "商机表数据模板";
				break;
			case PMPConstant.TABLE_RK:
				fileName += "入库表数据模板";
				break;
		}
		DeployFormMappingEntity deployFormMappingEntity = deployFormMappingService.getByMyKey(myKey);

		String externalParameterId = deployFormMappingEntity.getExternalParameterId();
		//获取项目表单配置
		YYExternalParameterEntity externalParameterEntity = yyExternalParameterService.getById(externalParameterId);
		if (ObjectUtil.isEmpty(externalParameterEntity)) {
			throw new RuntimeException("外部参数id错误");
		}
		List<YYBasicEntity> columList = yyBasicService.getHead(externalParameterEntity.getPlace());
		//这里的数据格式不满足文件导出的标准，需要修改
		List<String> oldColum = columList.stream().map(x -> x.getJsonValue()).collect(Collectors.toList());
		List<List<String>> colum = new LinkedList<>();
		String finalFileName = fileName;
		oldColum.forEach(x -> {
			LinkedList<String> strings = new LinkedList<>();
			strings.add(finalFileName);
			strings.add(x);
			colum.add(strings);
		});

		ArrayList<Object> Date = new ArrayList<>();

		response.setCharacterEncoding("utf-8");
		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
		try {
			fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			EasyExcel.write(response.getOutputStream()).head(colum).registerWriteHandler(new SimpleColumnWidthStyleStrategy(25)).sheet("模板").doWrite(Date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileName + ".xlsx";
	}

	/**
	 * 数据导出
	 *
	 * @param myKey
	 * @return
	 */
	@Override
	public String dowLoadExcel(String myKey, HttpServletResponse response) {
		String fileName = System.currentTimeMillis() + "";
		switch (myKey) {
			case PMPConstant.TABLE_SJ:
				fileName += "商机表数据";
				break;
			case PMPConstant.TABLE_RK:
				fileName += "入库表数据";
				break;
		}
		List<String> list = yyDataInfoService.myKeyList(myKey);
		DeployFormMappingEntity deployFormMappingEntity = deployFormMappingService.getByMyKey(myKey);

		String externalParameterId = deployFormMappingEntity.getExternalParameterId();
		//获取项目表单配置
		YYExternalParameterEntity externalParameterEntity = yyExternalParameterService.getById(externalParameterId);
		if (ObjectUtil.isEmpty(externalParameterEntity)) {
			throw new RuntimeException("外部参数id错误");
		}
		List<YYBasicEntity> columList = yyBasicService.getHead(externalParameterEntity.getPlace());
		//这里的数据格式不满足文件导出的标准，需要修改
		List<String> oldColum = columList.stream().map(x -> x.getJsonValue()).collect(Collectors.toList());
		List<List<String>> colum = new LinkedList<>();
		String finalFileName = fileName;
		oldColum.forEach(x -> {
			LinkedList<String> strings = new LinkedList<>();
			strings.add(finalFileName);
			strings.add(x);
			colum.add(strings);
		});
		List<CompletableFuture<HashMap<String, Object>>> futures = list.stream()
			.map(flowId ->
				CompletableFuture.supplyAsync(() ->
					basicLoadService.getParamData(myKey, flowId))).collect(Collectors.toList());
		List<HashMap<String, Object>> arrayList = futures.stream()
			.map(CompletableFuture::join) // 等同于 get()，但不会抛出 Checked 异常
			.collect(Collectors.toList());

		ArrayList<Object> Date = new ArrayList<>();
		//对导出的数据排序
		arrayList.forEach(x -> {
			String str = x.getOrDefault("paramData", "").toString();
			Map param = JSONObject.parseObject(str, Map.class);
			LinkedList<String> linkedList = new LinkedList<>();
			//表格数据按照表头进行排序
			columList.forEach(y -> {
				String jsonKey = y.getJsonKey();
				linkedList.add(param.getOrDefault(jsonKey, "").toString());
			});
			Date.add(linkedList);
		});

		/*String data = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
		String filePath = "D:\\" + data + "\\";
		String newFileName = filePath + System.currentTimeMillis() + fileName + ".xlsx";
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdir();
		}
		ExcelWriter excelWriter = EasyExcel.write(newFileName).registerWriteHandler(new SimpleColumnWidthStyleStrategy(25)).build();
		WriteSheet writeSheet = EasyExcel.writerSheet(fileName).build();
		writeSheet.setHead(colum);
		excelWriter.write(Date, writeSheet);
		excelWriter.finish();*/
		response.setCharacterEncoding("utf-8");
		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
		try {
			fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			EasyExcel.write(response.getOutputStream()).head(colum).registerWriteHandler(new SimpleColumnWidthStyleStrategy(25)).sheet("模板").doWrite(Date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileName + ".xlsx";
	}
}
